package com.joseph.websocket.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioServer {


    public static void main(String[] args) throws IOException {
        //打开一个serverchannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 8088));
        serverSocketChannel.configureBlocking(false);
        //打开一个selector
        Selector selector = Selector.open();
        //将channel注册到selector中
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isAcceptable()) {
                    System.out.println("connect");
                    SocketChannel accept = serverSocketChannel.accept();
                    accept.configureBlocking(false);
                    accept.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                } else if (selectionKey.isReadable()) {
                    System.out.println("read");
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(256);
                    int i = channel.read(buffer);
                    if (i != -1) {
                        String msg = new String(buffer.array()).trim();
                        System.out.println("NIO server received message =  " + msg);
                        System.out.println("NIO server reply =  " + msg);
                        channel.write(ByteBuffer.wrap(msg.getBytes()));
                    } else {
                        channel.close();
                    }
                } else if (selectionKey.isWritable()){

                } else {
                    System.out.println("other" + selectionKey.readyOps());
                }
                iterator.remove();
            }
        }
    }
}
